const fs = require('fs');
const path = require('path');
const chokidar = require('chokidar');

// 递归函数，用于获取指定目录下的所有 .vue 和 .js 文件路径
function getFiles(dir, exts) {
    let results = [];
    const files = fs.readdirSync(dir, { withFileTypes: true });

    for (const file of files) {
        const filePath = path.join(dir, file.name);
        if (file.isDirectory()) {
            results = results.concat(getFiles(filePath, exts));
        } else if (exts.some(ext => filePath.endsWith(ext))) {
            results.push(filePath);
        }
    }

    return results;
}

// 定义要扫描的目录和扩展名
const directories = [
    './src'
];

const extensions = ['.html', '.vue', '.js'];

// 获取初始文件路径
let allFilePaths = [];

directories.forEach(directory => {
    const paths = getFiles(path.resolve(__dirname, directory), extensions);
    allFilePaths = allFilePaths.concat(paths);
});

// 更新 tailwind.config.js 内容
function updateTailwindConfig() {
    const configContent = `
    module.exports = {
    content: [
        "./src/components/**/*.{js,vue}",
        "./src/views/**/*.{js,vue}", 
        "./src/layout/**/*.{js,vue}", 
        "./src/App.vue",
    ],
    theme: {
        extend: {}
    },
    plugins: [],
    }
`;

    fs.writeFileSync(path.resolve(__dirname, 'tailwind.config.js'), configContent, 'utf-8');
}

// 初始更新
updateTailwindConfig();

// 监听文件变化
const watcher = chokidar.watch(directories.map(dir => path.resolve(__dirname, dir)), {
    ignored: /(^|[\/\\])\../, // 忽略隐藏文件
    persistent: true
});

watcher.on('add', (filePath) => {
    if (extensions.some(ext => filePath.endsWith(ext))) {
        allFilePaths.push(filePath);
        updateTailwindConfig();
    }
});

watcher.on('unlink', (filePath) => {
    allFilePaths = allFilePaths.filter(path => path !== filePath);
    updateTailwindConfig();
});

watcher.on('change', (filePath) => {
    // 如果文件内容变化，不需要重新生成路径，只需更新时间戳即可 
    updateTailwindConfig();
});